package tech.yunland.shop.domain.websocket;



/**
 *李珂  likenamehaojie@hotmail.com
 * websocket消息处理类
 */
        import org.apache.commons.lang3.StringUtils;
        import org.slf4j.Logger;
        import org.slf4j.LoggerFactory;
        import org.springframework.web.socket.CloseStatus;
        import org.springframework.web.socket.TextMessage;
        import org.springframework.web.socket.WebSocketHandler;
        import org.springframework.web.socket.WebSocketMessage;
        import org.springframework.web.socket.WebSocketSession;

        import java.io.IOException;
        import java.util.ArrayList;
        import java.util.Date;

public class WsHandler  implements WebSocketHandler {
    private static final Logger log = LoggerFactory
            .getLogger(WsHandler.class);
    /**
     * 静态集合用于维护用户连接
     */
    private static final ArrayList<WebSocketSession> users;
    static {
        users = new ArrayList<WebSocketSession>();
    }

    public static ArrayList<WebSocketSession> getUsers() {
        return users;
    }
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        System.out.println("connect to the websocket success......");
        users.add(session);
        session.sendMessage(new TextMessage("Server:connected OK!"));
    }

    @Override
    public void handleMessage(WebSocketSession wss, WebSocketMessage<?> wsm) throws Exception {
        TextMessage returnMessage = new TextMessage(wsm.getPayload()+"");
        System.out.println(wss.getHandshakeHeaders().getFirst("Cookie"));
        String uname = (String) wss.getAttributes().get("uname");
        String responseMessage = returnMessage.getPayload();
        if(responseMessage.contains("&&")){//私信
            String[] info = responseMessage.split("&&");
            String toName = info[0];
            String content = info[1];
            this.handerPointToPoint(uname, toName, content);
        }else{
            TextMessage textMessage = null;
            if(responseMessage.contains("*update*")){
                textMessage = new TextMessage(responseMessage);
            }else {
                textMessage = new TextMessage(uname
                        + responseMessage);
            }

            this.sendMessageToUsers(textMessage);
           // wss.sendMessage(returnMessage);
        }


    }

    private void handerPointToPoint(String uname, String toName, String content) {
        TextMessage contentinfo = new TextMessage(toName + "说:" + content);
        if(toName.equals("all")){
            this.sendMessageToUsersNoIncludeSelf(contentinfo,uname);
        }else {
            this.sendMessageToUser(toName.trim(), contentinfo);

        }

    }

    private void sendMessageToUser(String username, TextMessage contentinfo) {
        for (WebSocketSession user : users) {
            String loginName  = (String) user.getAttributes().get(
                    "uname");
            if (StringUtils.isBlank(loginName)) {
                users.remove(user);
                continue;
            }
            if (loginName.equals(username)) {
                try {
                    if (user.isOpen()) {
                        user.sendMessage(contentinfo);
                        break;
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
                // break;
            }
        }
    }
    /**
     * 广播信息不包含发送者
     *
     * @param contentinfo
     *            信息内容
     * @param name
     *            发送者
     */
    private void sendMessageToUsersNoIncludeSelf(TextMessage contentinfo,
                                                 String name) {
        for (WebSocketSession user : users) {
            if (user.isOpen()) {
                try {
                    String  u = (String) user.getAttributes().get(
                            "uname");
//                    if (u == null) {
//                        log.warn("系统中的废弃连接");
//                        users.remove(user);
//                        continue;
//                    }
                  //  if (!u.equals(name)) {
                        user.sendMessage(contentinfo);
                    //}


                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

    }
    /**
     * 给所有在线用户发送消息
     *
     * @param message
     */
    public void sendMessageToUsers(TextMessage message) {
        for (WebSocketSession user : users) {
            if (user.isOpen()) {
                try {
                    user.sendMessage(message);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    @Override
    public void handleTransportError(WebSocketSession wss, Throwable thrwbl) throws Exception {
        if(wss.isOpen()){
            wss.close();
        }
        System.out.println("websocket connection closed......");
    }

    @Override
    public void afterConnectionClosed(WebSocketSession wss, CloseStatus cs) throws Exception {
        users.remove(wss);
        System.out.println("websocket connection closed......");
    }

    @Override
    public boolean supportsPartialMessages() {
        return false;
    }
}